package org.example.wx.user.web;

import lombok.extern.slf4j.Slf4j;
import org.example.wx.service.MinioService;
import org.example.wx.user.entity.WxUser;
import org.example.wx.user.service.WxUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@Slf4j
@RestController
@RequestMapping("/api/wx/upload")
public class FileUploadController {

    @Autowired
    private MinioService minioService;
    
    @Autowired
    private WxUserService wxUserService;

    /**
     * 上传头像
     */
    @PostMapping("/avatar")
    public ResponseEntity<?> uploadAvatar(@RequestParam("file") MultipartFile file,
                                         @RequestHeader("Authorization") String token) {
        try {
            // 验证文件类型
            if (!isImageFile(file)) {
                Map<String, Object> error = new HashMap<>();
                error.put("message", "只支持图片文件");
                return ResponseEntity.badRequest().body(error);
            }

            // 验证文件大小（10MB）
            if (file.getSize() > 10 * 1024 * 1024) {
                Map<String, Object> error = new HashMap<>();
                error.put("message", "文件大小不能超过10MB");
                return ResponseEntity.badRequest().body(error);
            }

            // 上传到MinIO
            String fileUrl = minioService.uploadFile(file, "avatars");

            Map<String, Object> result = new HashMap<>();
            result.put("url", fileUrl);
            result.put("message", "上传成功");

            log.info("Avatar uploaded successfully: {}", fileUrl);
            
            // 更新用户信息
            try {
                // 从token中提取用户ID
                Long userId = extractUserIdFromToken(token);
                
                // 创建更新请求Map
                Map<String, Object> updateRequest = new HashMap<>();
                updateRequest.put("avatarUrl", fileUrl);
                
                // 调用用户服务更新头像URL
                wxUserService.updateProfile(userId, updateRequest);
                log.info("用户头像URL已更新到数据库: {}", fileUrl);
            } catch (Exception e) {
                log.warn("更新用户头像URL失败，但文件上传成功: {}", e.getMessage());
            }
            
            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("Avatar upload failed", e);
            Map<String, Object> error = new HashMap<>();
            error.put("message", "上传失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    /**
     * 从token中提取用户ID
     */
    private Long extractUserIdFromToken(String token) {
        // 简单的token解析，实际项目中应该使用JWT等安全方案
        if (token.startsWith("user-")) {
            return Long.parseLong(token.substring(5));
        } else if (token.startsWith("wx-")) {
            // 对于微信登录的用户，需要通过openId查找
            String openId = token.substring(3);
            Optional<WxUser> user = wxUserService.findByOpenId(openId);
            if (user.isPresent()) {
                return user.get().getId();
            }
        }
        throw new RuntimeException("无效的token");
    }

    /**
     * 上传通用图片
     */
    @PostMapping("/image")
    public ResponseEntity<?> uploadImage(@RequestParam("file") MultipartFile file,
                                        @RequestHeader("Authorization") String token) {
        try {
            // 验证文件类型
            if (!isImageFile(file)) {
                Map<String, Object> error = new HashMap<>();
                error.put("message", "只支持图片文件");
                return ResponseEntity.badRequest().body(error);
            }

            // 验证文件大小（10MB）
            if (file.getSize() > 10 * 1024 * 1024) {
                Map<String, Object> error = new HashMap<>();
                error.put("message", "文件大小不能超过10MB");
                return ResponseEntity.badRequest().body(error);
            }

            // 上传到MinIO
            String fileUrl = minioService.uploadFile(file, "images");

            Map<String, Object> result = new HashMap<>();
            result.put("url", fileUrl);
            result.put("message", "上传成功");

            log.info("Image uploaded successfully: {}", fileUrl);
            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("Image upload failed", e);
            Map<String, Object> error = new HashMap<>();
            error.put("message", "上传失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    /**
     * 验证是否为图片文件
     */
    private boolean isImageFile(MultipartFile file) {
        String contentType = file.getContentType();
        return contentType != null && (
                contentType.startsWith("image/jpeg") ||
                contentType.startsWith("image/png") ||
                contentType.startsWith("image/gif") ||
                contentType.startsWith("image/webp") ||
                contentType.startsWith("image/bmp")
        );
    }
}
